package com.example.tool.util;

import com.example.tool.erp.sdk.Client;
import com.example.tool.erp.sdk.Pager;
import com.example.tool.erp.sdk.WdtErpException;
import com.example.tool.erp.sdk.api.aftersales.RefundAPI;
import com.example.tool.erp.sdk.api.aftersales.dto.RefundSearchRequest;
import com.example.tool.erp.sdk.api.aftersales.dto.RefundSearchResponse;
import com.example.tool.erp.sdk.api.goods.GoodsAPI;
import com.example.tool.erp.sdk.api.goods.dto.GoodsSearchRequest;
import com.example.tool.erp.sdk.api.goods.dto.GoodsSearchResponse;
import com.example.tool.erp.sdk.api.sales.TradeAPI;
import com.example.tool.erp.sdk.api.sales.dto.TradeQueryGetLogRequest;
import com.example.tool.erp.sdk.api.sales.dto.TradeQueryRequest;
import com.example.tool.erp.sdk.api.sales.dto.TradeQueryResponse;
import com.example.tool.erp.sdk.api.setting.SettingAPI;
import com.example.tool.erp.sdk.api.setting.dto.WarehouseQueryRequest;
import com.example.tool.erp.sdk.api.setting.dto.WarehouseQueryResponse;
import com.example.tool.erp.sdk.api.wms.StockAPI;
import com.example.tool.erp.sdk.api.wms.dto.StockSearch2Request;
import com.example.tool.erp.sdk.api.wms.dto.StockSearch2Response;
import com.example.tool.erp.sdk.api.wms.stockin.StockinAPI;
import com.example.tool.erp.sdk.api.wms.stockin.dto.PurchaseStockinSearchRequest;
import com.example.tool.erp.sdk.api.wms.stockin.dto.PurchaseStockinSearchResponse;
import com.example.tool.erp.sdk.api.wms.stockout.StockoutAPI;
import com.example.tool.erp.sdk.api.wms.stockout.dto.SalesStockoutRequest;
import com.example.tool.erp.sdk.api.wms.stockout.dto.SalesStockoutResponse;
import com.example.tool.erp.sdk.api.wms.stockspec.StockSpecAPI;
import com.example.tool.erp.sdk.api.wms.stockspec.dto.StockSpecChangeHistoryQueryRequest;
import com.example.tool.erp.sdk.api.wms.stockspec.dto.StockSpecChangeHistoryQueryResponse;
import com.example.tool.erp.sdk.impl.ApiFactory;
import com.example.tool.erp.sdk.impl.DefaultClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import shade.com.alibaba.fastjson2.JSON;
import shade.com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 旺店通
 */
@Slf4j
public class WDTUtil {
    private static final String sId = "yibei3";
    private static final String key = "yibei3-ot";
    private static final String secret = "8fb90b61afa4060dffd316cefd05b077:956362003445257814e19c6f553597ff";

    /**
     * 物流单号查询订单
     *
     * @param logisticsNo
     * @return
     */
    public static TradeQueryResponse.OrderItem logisticsNoQueryOrder(String logisticsNo) {
        // Client client = DefaultClient.get("wdtapi3", "test", "test");
        TradeQueryRequest request = new TradeQueryRequest();
        // request.setSrcTid("tid-D9kO2OooUy");
        request.setLogisticsNo(logisticsNo);
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        TradeAPI tradeApi = ApiFactory.get(client, TradeAPI.class);
        TradeQueryResponse response = tradeApi.query(request, new Pager(20, 0, true));
        if (response == null || response.getTotalCount() <= 0) {
            return null;
        }
        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response.getOrders().get(0);
    }


    /**
     * 物流单号查询订单
     *
     * @return
     */
    public static TradeQueryResponse
    queryOrderList(String startTime, String endTime, String status, Integer pageSize, Integer pageNo) {
        // Client client = DefaultClient.get("wdtapi3", "test", "test");
        TradeQueryRequest request = new TradeQueryRequest();
        request.setStartTime(startTime);
        request.setEndTime(endTime);
        if (StringUtils.isNotBlank(status)) {
            request.setStatus(status);
        }
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        TradeAPI tradeApi = ApiFactory.get(client, TradeAPI.class);
        TradeQueryResponse response = tradeApi.query(request, new Pager(pageSize, pageNo, true));
        if (response == null || response.getTotalCount() <= 0) {
            return null;
        }
        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response;
    }


    public static List<TradeQueryResponse.OrderItem> tradeNoQueryOrder(String tradeNo, Integer pageSize, Integer pageNo) {
        TradeQueryRequest request = new TradeQueryRequest();
        request.setTradeNo(tradeNo);
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        TradeAPI tradeApi = ApiFactory.get(client, TradeAPI.class);
        TradeQueryResponse response = tradeApi.query(request, new Pager(pageSize, pageNo, true));
        if (response == null || response.getTotalCount() <= 0) {
            return null;
        }
        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response.getOrders();
    }

    public static List<TradeQueryResponse.OrderItem> srcTidQueryOrder(String srcTid, Integer pageSize, Integer pageNo) {
        TradeQueryRequest request = new TradeQueryRequest();
        request.setSrcTid(srcTid);
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        TradeAPI tradeApi = ApiFactory.get(client, TradeAPI.class);
        TradeQueryResponse response = tradeApi.query(request, new Pager(pageSize, pageNo, true));
//        if (response == null || response.getTotalCount() <= 0)
//        {return null;}
        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response.getOrders();
    }

    //仓库列表
    public static List<WarehouseQueryResponse.WarehouseDto> queryWarehouse() {
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        SettingAPI settingApi = ApiFactory.get(client, SettingAPI.class);
        WarehouseQueryRequest request = new WarehouseQueryRequest();
        WarehouseQueryResponse response = settingApi.queryWarehouse(request, new Pager(100, 0, true));
        if (response.getTotal() == null || response.getTotal() == 0) {
            return new ArrayList<>();
        }
        return response.getWarehouseList();
    }

    /**
     * 销售出库单查询
     *
     * @param endTime
     * @param startTime
     * @param status
     * @param statusType
     */
    public static SalesStockoutResponse queryWithDetail(String startTime, String endTime, Byte statusType, String status, Integer pageSize, Integer pageNo) {
        SalesStockoutRequest request = new SalesStockoutRequest();
        request.setStartTime(startTime);
        request.setEndTime(endTime);
        request.setStatus(status);
        request.setStatusType(statusType);
        request.setNeedSn(true);
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        SalesStockoutResponse response = new SalesStockoutResponse();
        try {
            response = ApiFactory.get(client, StockoutAPI.class).querySales(request, new Pager(pageSize, pageNo, true));
        } catch (WdtErpException e) {
            throw new RuntimeException(e);
        }
        if (response == null || response.getTotal() <= 0) {
            response.setTotal(0);
            response.setOrderList(new ArrayList<>());
            return response;
        }
        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response;
    }

//    public static void main(String[] args) {
//         System.out.println(queryWarehouse().stream().map(e->e.getWarehouseNo()+" : "+e.getName()).collect(Collectors.joining(",")));
////         System.out.println(tradeNoQueryOrder("JY2025070925125",1,0).get(0));
////        List<WarehouseQueryResponse.WarehouseDto> warehouseDtos = queryWarehouse();
////        for(WarehouseQueryResponse.WarehouseDto w: warehouseDtos){
////
////        System.out.println( w.getWarehouseNo()+" "+w.getName());
////        }
////        SalesStockoutResponse salesStockoutResponse = queryWithDetail2("76717367982034", 10, 0);
////        System.out.println(DateUtil.toDateToStr(salesStockoutResponse.getOrderList().get(0).getCreated()));
//    }

    /**
     * 销售出库单查询
     *
     * @param logisticsNo
     * @param pageSize
     * @param pageNo
     */
    public static SalesStockoutResponse queryWithDetail2(String logisticsNo, Integer pageSize, Integer pageNo) {
        SalesStockoutRequest request = new SalesStockoutRequest();
        request.setLogisticsNo(logisticsNo);
        request.setNeedSn(true);
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        SalesStockoutResponse response = new SalesStockoutResponse();
        try {
            response = ApiFactory.get(client, StockoutAPI.class).querySales(request, new Pager(pageSize, pageNo, true));
        } catch (WdtErpException e) {
            throw new RuntimeException(e);
        }
        if (response == null || response.getTotal() <= 0) {
            response.setTotal(0);
            response.setOrderList(new ArrayList<>());
            return response;
        }
        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response;
    }

    /**
     * 销售出库单查询
     */
    public static SalesStockoutResponse queryWithDetail3(String stockoutNo) {
        SalesStockoutRequest request = new SalesStockoutRequest();
        request.setStockoutNo(stockoutNo);
        request.setNeedSn(true);
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        SalesStockoutResponse response = new SalesStockoutResponse();
        try {
            response = ApiFactory.get(client, StockoutAPI.class).querySales(request, new Pager(10, 0, true));
        } catch (WdtErpException e) {
            throw new RuntimeException(e);
        }
        if (response == null || response.getTotal() <= 0) {
            response.setTotal(0);
            response.setOrderList(new ArrayList<>());
            return response;
        }
        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response;
    }


    /**
     * 订单日志查询
     */
    public static JSONObject tradeQueryGetLog(String tradeNo) {
        TradeQueryGetLogRequest request = new TradeQueryGetLogRequest();
        request.setTradeNo(tradeNo);


        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        JSONObject response = ApiFactory.get(client, TradeAPI.class).getLog(request);


        // 休眠1000毫秒（1秒）
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
        return response;
    }

    public static StockSearch2Response stockSpecSearch2(String startSearchTime, String endSearchTime, int pageSize, int pageNo) {
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        StockAPI stockAPI = ApiFactory.get(client, StockAPI.class);
        StockSearch2Request request = new StockSearch2Request();
        request.setStartTime(startSearchTime);
        request.setEndTime(endSearchTime);
        request.setMask(1);
//        StockSearch2Response response = stockAPI.search2(request, new Pager(pageSize, pageNo, true));
//        if (response.getTotal() <= 0)
//        {
//            return new ArrayList<>();
//        }

//        List<StockSearch2Response.Detail> detailList = response.getDetailList();
        return stockAPI.search2(request, new Pager(pageSize, pageNo, true));
    }

    public static void searchPurchaseStockIn(String startSearchTime, String endSearchTime) throws WdtErpException {
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        StockinAPI stockAPI = ApiFactory.get(client, StockinAPI.class);
        int pageSize = 2000;
        Pager pager = new Pager(pageSize, 0, true);
        PurchaseStockinSearchRequest request = new PurchaseStockinSearchRequest();
        request.setStartTime(startSearchTime);
        request.setEndTime(endSearchTime);
        request.setStatus(80);
        PurchaseStockinSearchResponse response = stockAPI.searchPurchaseStockin(request, pager);
        Integer total = response.getTotal();
        if (null == total || pageSize >= total) {
            System.out.println("处理数据");
            return;
        }

        int totalPage = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1) - 1;
        pager.setCalcTotal(false); //后续翻页不需要计算总条数, 可以大大减少请求时间
        for (int i = totalPage; i >= 0; i--) {// 从后向前翻页
            pager.setPageNo(i);
            System.out.print("pager: page_size:" + pageSize + "  page_no: " + i + "  ");
            response = stockAPI.searchPurchaseStockin(request, pager);
            System.out.println(response.getOrderList());
        }
    }

    public static List<StockSpecChangeHistoryQueryResponse.Data> queryStockSpecChangeHistory(String specNo, String startSearchTime, String endSearchTime) throws WdtErpException {
        List<StockSpecChangeHistoryQueryResponse.Data> dataList = new ArrayList<>();
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        StockSpecAPI stockAPI = ApiFactory.get(client, StockSpecAPI.class);
        int pageSize = 500;
        Pager pager = new Pager(pageSize, 0, true);
        StockSpecChangeHistoryQueryRequest request = new StockSpecChangeHistoryQueryRequest();
        request.setStartDate(startSearchTime);
        request.setEndDate(endSearchTime);
        request.setSpecNo(specNo);
        request.setType(1);
        request.setDefect(false);
        log.info("库存变化查询入参:{}", JSON.toJSONString(request));
        StockSpecChangeHistoryQueryResponse response = stockAPI.queryChangeHistory(request, pager);
        log.info("库存变化查询结果:{}", JSON.toJSONString(response));
        Integer total = response.getTotal();
        dataList.addAll(response.getDataList());
//        if (null == total || pageSize >= total) {
//            return dataList;
//        }
//        int totalPage = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1) - 1;
//        pager.setCalcTotal(false); //后续翻页不需要计算总条数, 可以大大减少请求时间
//        for (int i = 1; i <= totalPage; i++) {
//            pager.setPageNo(i);
//            log.info("库存变化继续查询入参:{}", JSON.toJSONString(request));
//            response = stockAPI.queryChangeHistory(request, pager);
//            log.info("库存变化继续查询结果:{}", JSON.toJSONString(response));
//            dataList.addAll(response.getDataList());
//        }
        return dataList;
    }

    public static GoodsSearchResponse goodsSearchSpecNo(String specNo) {
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        GoodsSearchRequest request = new GoodsSearchRequest();
        request.setSpecNo(specNo);
        GoodsAPI goodsApi = ApiFactory.get(client, GoodsAPI.class);
        try {
            // 休眠1000毫秒（1秒）
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
        }
        GoodsSearchResponse response = goodsApi.search(request, new Pager(10, 0, true));
        return response;
    }

    public static RefundSearchResponse searchRefund(String modifiedFrom, String modifiedTo, String type, String status, int pageSize, int pageNo) {
        RefundSearchRequest request = new RefundSearchRequest();
        request.setModifiedFrom(modifiedFrom);
        request.setModifiedTo(modifiedTo);
        if (StringUtils.isNotBlank(type)) {
            request.setType(Byte.parseByte(type));
        }
        if (StringUtils.isNotBlank(status)) {
            request.setStatus(Byte.parseByte(status));
        }
        Client client = DefaultClient.get(sId, "http://wdt.wangdian.cn/", key, secret);
        RefundAPI refundApi = ApiFactory.get(client, RefundAPI.class);
        return refundApi.search(request, new Pager(pageSize, pageNo, true));
    }


    public static void main(String[] args) {
//        RefundSearchRequest request = new RefundSearchRequest();
//        request.setModifiedFrom("2025-8-1 00:00:00");
//        request.setModifiedTo("2025-8-3 23:26:31");
//        Client client = DefaultClient.get(sId,"http://wdt.wangdian.cn/",key,secret);
//        RefundAPI refundApi = ApiFactory.get(client, RefundAPI.class);
//        Pager pager = new Pager(10, 0, true);
//        RefundSearchResponse response = refundApi.search(request,pager);

        System.out.println(searchRefund("2025-8-1 00:00:00", "2025-8-3 23:26:31", null, null, 10, 0));
//        System.out.println(logisticsNoQueryOrder("434682257458713"));

//        Client client = DefaultClient.get(sId,"http://wdt.wangdian.cn/",key,secret);
//        GoodsSearchRequest request = new GoodsSearchRequest();
//        request.setGoodsNo("210426790");
//        GoodsAPI goodsApi = ApiFactory.get(client, GoodsAPI.class);
//        GoodsSearchResponse response = goodsApi.search(request, new Pager(10, 0, true));
//
//          System.out.println(response.getGoodsInfos().get(0).getSpecDtos().get(0).getProp6());
//        System.out.println(stockSpecSearch2("2022-05-01 03:00:00","2022-05-06 03:00:00"));
//        List<TradeQueryResponse.OrderItem>apiOrderItems=WDTUtil.srcTidQueryOrder("250715-111578979860197",50,0);
//        System.out.println(apiOrderItems.get(0).toString());
//        apiOrderItems=WDTUtil.srcTidQueryOrder("250715-541411274260197",50,0);
//        System.out.println(apiOrderItems.get(0).getTradeNo());
//        apiOrderItems=WDTUtil.srcTidQueryOrder("250715-290062374420197",50,0);
//        System.out.println(apiOrderItems.get(0).getTradeNo());
//        apiOrderItems=WDTUtil.srcTidQueryOrder("250715-111578979860197,250715-541411274260197",50,0);
//        System.out.println(apiOrderItems.get(0).getTradeNo());
//        apiOrderItems=WDTUtil.srcTidQueryOrder("250715-541411274260197,250715-290062374420197",50,0);
//        System.out.println(apiOrderItems.get(0).getTradeNo());
//        apiOrderItems=WDTUtil.srcTidQueryOrder("250715-111578979860197,250715-541411274260197,250715-290062374420197",50,0);
//        System.out.println(apiOrderItems.get(0).getTradeNo());
    }

}

